export default{
	namespaced: true,
	
	state:()=>({
		//购物车数组，用来存储购物车中每个商品的信息对象
		//包含六个属性
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	
	mutations:{
		addToCart(state,goods){
			const findResult=state.cart.find(x=>x.goods_id === goods.goods_id)
			// console.log(findResult)
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			
			//通过commit方法，调用m_cart命名空间下的saveToStorage方法
			this.commit('m_cart/saveToStorage')
			// console.log(state.cart)
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		//更新购物车中商品的勾选状态
		updateGoodsState(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsCount(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		removeGoodsById(state,goods_id){
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			this.commit('m_cart/saveToStorage')
		}
	},
	getters:{
		total(state){
			let c=0
			state.cart.forEach(x => c+=x.goods_count)
			return c
		}
	}
}